{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a9ca600f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C:\\Users\\zhang C:\\Users\\zhang\\.vntrader\n",
      "C:\\Users\\zhang C:\\Users\\zhang\\.vntrader\n"
     ]
    }
   ],
   "source": [
    "import multiprocessing\n",
    "import sys\n",
    "from time import sleep\n",
    "from datetime import datetime, time\n",
    "from logging import INFO\n",
    "\n",
    "from vnpy.event import EventEngine\n",
    "from vnpy.trader.setting import SETTINGS\n",
    "from vnpy.trader.engine import MainEngine\n",
    "\n",
    "from vnpy.gateway.ctp import CtpGateway\n",
    "from vnpy.app.cta_strategy import CtaStrategyApp\n",
    "from vnpy.app.cta_strategy.base import EVENT_CTA_LOG\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "813f3fcc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "启动CTA策略守护父进程\n",
      "启动子进程\n",
      "子进程启动成功\n"
     ]
    }
   ],
   "source": [
    "\n",
    "SETTINGS[\"log.active\"] = True\n",
    "SETTINGS[\"log.level\"] = INFO\n",
    "SETTINGS[\"log.console\"] = True\n",
    "\n",
    "\n",
    "ctp_setting = {\n",
    "    \"用户名\": \"\",\n",
    "    \"密码\": \"\",\n",
    "    \"经纪商代码\": \"\",\n",
    "    \"交易服务器\": \"\",\n",
    "    \"行情服务器\": \"\",\n",
    "    \"产品名称\": \"\",\n",
    "    \"授权编码\": \"\",\n",
    "    \"产品信息\": \"\"\n",
    "}\n",
    "\n",
    "\n",
    "# Chinese futures market trading period (day/night)\n",
    "DAY_START = time(8, 45)\n",
    "DAY_END = time(15, 0)\n",
    "\n",
    "NIGHT_START = time(20, 45)\n",
    "NIGHT_END = time(2, 45)\n",
    "\n",
    "\n",
    "def check_trading_period():\n",
    "    \"\"\"\"\"\"\n",
    "    current_time = datetime.now().time()\n",
    "\n",
    "    trading = False\n",
    "    if (\n",
    "        (current_time >= DAY_START and current_time <= DAY_END)\n",
    "        or (current_time >= NIGHT_START)\n",
    "        or (current_time <= NIGHT_END)\n",
    "    ):\n",
    "        trading = True\n",
    "\n",
    "    return trading\n",
    "\n",
    "\n",
    "def run_child():\n",
    "    \"\"\"\n",
    "    Running in the child process.\n",
    "    \"\"\"\n",
    "    SETTINGS[\"log.file\"] = True\n",
    "\n",
    "    event_engine = EventEngine()\n",
    "    main_engine = MainEngine(event_engine)\n",
    "    main_engine.add_gateway(CtpGateway)\n",
    "    cta_engine = main_engine.add_app(CtaStrategyApp)\n",
    "    main_engine.write_log(\"主引擎创建成功\")\n",
    "\n",
    "    log_engine = main_engine.get_engine(\"log\")\n",
    "    event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)\n",
    "    main_engine.write_log(\"注册日志事件监听\")\n",
    "\n",
    "    main_engine.connect(ctp_setting, \"CTP\")\n",
    "    main_engine.write_log(\"连接CTP接口\")\n",
    "\n",
    "    sleep(10)\n",
    "\n",
    "    cta_engine.init_engine()\n",
    "    main_engine.write_log(\"CTA策略初始化完成\")\n",
    "\n",
    "    cta_engine.init_all_strategies()\n",
    "    sleep(60)   # Leave enough time to complete strategy initialization\n",
    "    main_engine.write_log(\"CTA策略全部初始化\")\n",
    "\n",
    "    cta_engine.start_all_strategies()\n",
    "    main_engine.write_log(\"CTA策略全部启动\")\n",
    "\n",
    "    while True:\n",
    "        sleep(10)\n",
    "\n",
    "        trading = check_trading_period()\n",
    "        if not trading:\n",
    "            print(\"关闭子进程\")\n",
    "            main_engine.close()\n",
    "            sys.exit(0)\n",
    "\n",
    "\n",
    "def run_parent():\n",
    "    \"\"\"\n",
    "    Running in the parent process.\n",
    "    \"\"\"\n",
    "    print(\"启动CTA策略守护父进程\")\n",
    "\n",
    "    child_process = None\n",
    "\n",
    "    while True:\n",
    "        trading = check_trading_period()\n",
    "\n",
    "        # Start child process in trading period\n",
    "        if trading and child_process is None:\n",
    "            print(\"启动子进程\")\n",
    "            child_process = multiprocessing.Process(target=run_child)\n",
    "            child_process.start()\n",
    "            print(\"子进程启动成功\")\n",
    "\n",
    "        # 非记录时间则退出子进程\n",
    "        if not trading and child_process is not None:\n",
    "            if not child_process.is_alive():\n",
    "                child_process = None\n",
    "                print(\"子进程关闭成功\")\n",
    "\n",
    "        sleep(5)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    run_parent()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a20db864",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
